#!/usr/bin/env python
# Copyright (c) 2008 Chris Moyer http://coredumped.org
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

def get_function(session, f_name):
	"""
	Get function f_name (starting point of session)
	"""
	cmd_list = f_name.split(".")
	func = session[cmd_list.pop(0)]
	for cmd in cmd_list:
		func = getattr(func, cmd)
	return func

if __name__ == "__main__":
	import sys
	sys.path.append(".")
	from optparse import OptionParser
	from paste import httpserver
	import boto_web
	from boto_web.environment import Environment

	parser = OptionParser(usage="usage: %prog [options] application")
	parser.add_option("-e", "--environment", dest="env", default=None, help="Environment file to use")
	parser.add_option("-p", "--port", dest="port", default="8080", help="Port to run on (default 8080)")
	parser.add_option("--host", dest="hostname", default="localhost", help="Hostname to run on (default localhost)")
	parser.add_option("--init", dest="init", action="store_true", default=False, help="Initialize the Databases (Currently only works with SDB)")
	parser.add_option("--add-user", dest="add_user", action="store_true", default=False, help="Add a user")
	parser.add_option("--shell", dest="shell", action="store_true", default=False, help="Run the interactive command-line shell")
	parser.add_option("-v", action="count", dest="verbose", default=0)
	(options, args) = parser.parse_args()

	e = Environment(args[0], options.env)
	import boto
	boto.config = e.config

	if (options.init == True):
		print "Initializing Databases"
		sdb = boto.connect_sdb(
			e.config['DB']['db_user'], 
			e.config['DB']['db_passwd'], 
			port=e.config['DB'].get("db_port", None), 
			host=e.config['DB'].get("db_host", "sdb.amazonaws.com"),
			is_secure=e.config['DB'].get("enable_ssl", True)
			)
		print "Creating domain: %s" % e.config['DB']['db_name']
		sdb.create_domain(e.config['DB'].get("db_name"))
		for db in e.config['DB'].values():
			if isinstance(db, dict) and db.get("db_name", None) != None:
				print "Creating domain: %s" % db.get("db_name")
				sdb.create_domain(db['db_name'])
		print "Done"
		exit(0)

	if (options.add_user == True):
		from boto_web.resources.user import User
		u = User()
		u.username = raw_input("Username: ")
		u.password = raw_input("Password: ")
		u.put()
		print "Done"
		exit(0)

	if (options.shell == True):
		import code
		import readline
		from boto_web.resources.user import User
		code.interact(local={
			"env": e,
			"boto": boto,
			"User": User
		})
		exit(0)

	from boto_web.appserver.url_mapper import URLMapper
	from boto_web.appserver.filter_mapper import FilterMapper
	from boto_web.appserver.cache_layer import CacheLayer
	from boto_web.appserver.auth_layer import AuthLayer
	mapper = AuthLayer(
					app=FilterMapper(
						app=CacheLayer(
							app=URLMapper(e), env=e), 
						env=e), 
					env=e)

	# Use CherryPy if available
	try:
		from cherrypy import wsgiserver
		print "Using CherryPyWSGIServer"
		s = wsgiserver.CherryPyWSGIServer((options.hostname, int(options.port)),mapper)
		try:
			s.start()
		finally:
			s.stop()
	except ImportError:
		print "CherryPy not available, using paste.httpserver instead"
		from paste import httpserver
		httpserver.serve(mapper, 
			host=options.hostname, 
			port=int(options.port), 
			daemon_threads=True,
			socket_timeout=60,
			protocol_version="HTTP/1.1",
		)
